package com.lmm.rpc.client.autoconfig;

import com.lmm.rpc.client.processor.RpcClientProcessor;
import com.lmm.rpc.core.cluster.ILoadBalancer;
import com.lmm.rpc.core.cluster.RandomBalance;
import com.lmm.rpc.core.proxy.JdkProxyFactory;
import com.lmm.rpc.core.proxy.ProxyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @title: RpcClientAutoConfig
 * @Description: rpc 客户端自动配置类
 * @Author Lmm
 * @Date: 2022/10/8 16:29
 * @Version 1.0
 */
@Configuration
public class RpcClientAutoConfig {

    @Bean
    public RpcClientProperties rpcClientProperties(Environment environment) {
        BindResult<RpcClientProperties> result = Binder.get(environment).bind("rpc.consumer", RpcClientProperties.class);
        return result.get();
    }


    /**
     * 默认使用jdk代理
     * */
    @Bean(name = "jdkProxyFactory")
    @ConditionalOnMissingBean
    public JdkProxyFactory proxyFactory(){
        return new JdkProxyFactory();
    }

    /**
     * 负载默认
     * */
    @Bean(name = "randomBalance")
    public ILoadBalancer loadBalancer(){
        return new RandomBalance();
    }

    /**
     * beanFactory的后置处理器
     * */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({RpcClientProperties.class,JdkProxyFactory.class})
    public RpcClientProcessor rpcClientProcessor(@Autowired JdkProxyFactory proxyFactory,
                                                 @Autowired RpcClientProperties properties)
    {
        return new RpcClientProcessor(proxyFactory,properties);
    }

}
